Laravel / Controller / Validation Rules
Validation Rule
-
Rules
#1) Before Or Equal (Date) – before_or_equal:date
This validation rule only allows using a value preceding or equal to the given date.
#2) Between – between:min,maxThis validation rule only allows using a size between the given min and max.
#3) Date – dateThis validation rule only allows using a valid, non-relative date according to the strtotime PHP function.
#4) Date Format – date_format:formatUnder this validation rule, the field must match the given format.
#5) Different – different:fieldUnder this validation rule, the field must have a different value than the field.
#6) Distinct – distinctWhen working with arrays, under this validation rule, the field must not have any duplicate values.
#7) Email – emailUnder this validation rule, the field must be formatted as an email address.
#8) Image (File) – imageUnder this validation rule, the field must be an image (jpeg, png, bmp, gif, svg, or webp).
#9) Nullable – nullableUnder this validation rule, the field must be null.,
#10) Numeric – numericUnder this validation rule, the field must be numeric.
#11) Regular Expression – regex:patternUnder this validation rule, the field must match the given regular expression.
#12) Required – requiredUnder this validation rule, the field must be present in the input data and not empty.
#13) Size – size:valueUnder this validation rule, the field must have a size matching the given value.
#14) Sometimes – sometimesThis validation rule runs validation checks against a field only if that field is present in the input array.
#15) URL – urlUnder this validation rule, the field must be a valid URL.
-
Example
1. controller
namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Student; class StudentController extends Controller { public function create() { return view('create'); } public function store(Request $request) { $input = $request->all(); $request->validate([ 'title' => 'required', 'name' => 'required|max:255', 'bday' => 'required|date', 'age' => 'required|numeric', 'gender' => 'required', 'phone' => 'required|min:10', 'address' => 'required|max:255', 'email' => 'required|email|max:255', 'password' => 'required|min:6|max:255', 't&c' => 'required', ]); $input['password'] = bcrypt($input['password']); Student::create($input); return back()->with('success','Successfully registered a new student!'); } } 2. in view form
@if (count($errors) > 0) -
@foreach ($errors->all() as $error)
- {{ $error }} @endforeach
{{ $message }}@endif